package com.ng.desktop.fpa.persistence;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xBaseJ.DBF;

import com.linuxense.javadbf.DBFReader;

public class NGDBFPersistence<T> {

	private static final Logger LOG = LoggerFactory.getLogger(NGDBFPersistence.class);

	public List<T> getObjectsFromDBFPlain(String pathToDBF, DBFBuilder<T> dbfBuilder) {

		List<T> rowObjects = new ArrayList<T>();
		try {
			DBF classDB = new DBF(pathToDBF);

			LOG.info("Size of " + pathToDBF + " :" + classDB.getRecordCount());

			for (int i = 1; i <= classDB.getRecordCount(); i++) {
				classDB.read();

				rowObjects.add(dbfBuilder.build(classDB));

				if (i % 1000 == 0) {
					LOG.debug("Heap Free Size: " + (Runtime.getRuntime().freeMemory() / (1024 * 1024)) + " Bloque: " + i);
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rowObjects;
	}

	public List<T> getObjectsFromDBF(String pathToDBF, DBFBuilder<T> dbfBuilder) {

		List<T> rowObjects = new ArrayList<T>();
		try {

			InputStream inputStream = new FileInputStream(pathToDBF);
			DBFReader reader = new DBFReader(inputStream);

			Object[] rowObject;

			int i = 0;

			while ((rowObject = reader.nextRecord()) != null) {

				rowObjects.add(dbfBuilder.build(rowObject));
				i++;

			}
			LOG.info("Size of " + pathToDBF + " :" + i);

			inputStream.close();
		} catch (Exception e) {

			System.out.println(e.getMessage());
		}
		return rowObjects;
	}
}